#include <stdio.h>
#include <string.h>
#include "message.h"

void cleanTrailingSpace( char * chaine )
{
	char * pchaine = strchr( chaine , '\0' );
	if ( strlen( chaine ) > 0 )
	{
		while ( pchaine != chaine )
		{
			pchaine --;
			if ( *pchaine == ' ' )
			{
				*pchaine = '\0';
			}
			else
			{
				break;
			}
		}
	}		
}

void serializeMessage( char * buffer, Message * msg)
{
	sprintf( buffer, "%-*s%-*s%-*s" 
					, (int) (sizeof(msg->source) - 1), msg->source
					, (int) (sizeof(msg->subject) - 1), msg->subject
					, (int) (sizeof(msg->message) - 1), msg->message );

#if defined DEBUG
	printf("[serializeMessage][source] : [%s]\n", msg->source );
	printf("[serializeMessage][subject] : [%s]\n", msg->subject );
	printf("[serializeMessage][message] : [%s]\n", msg->message );
	printf("[serializeMessage][buffer] : [%s]\n", buffer );
#endif

					
}

void  unSerializeMessage( char * buffer, Message * msg)
{
	memcpy( msg->source, buffer, sizeof( msg->source ) );
	msg->source[  sizeof( msg->source ) - 1] = '\0';
	memcpy( msg->subject, buffer  + sizeof( msg->source ) - 1, sizeof( msg->subject ) );
	msg->subject[  sizeof( msg->subject ) - 1] = '\0';
	memcpy( msg->message, buffer  + sizeof( msg->source ) + sizeof( msg->subject ) - 2, sizeof( msg->message ) );
	msg->message[  sizeof( msg->message ) - 1] = '\0';
	
	
	cleanTrailingSpace( msg->source );
	cleanTrailingSpace( msg->subject );
	cleanTrailingSpace( msg->message );

#if defined DEBUG
	printf("[unSerializeMessage][buffer] : [%s]\n", buffer );
	printf("[unSerializeMessage][source] : [%s]\n", msg->source );
	printf("[unSerializeMessage][subject] : [%s]\n", msg->subject );
	printf("[unSerializeMessage][message] : [%s]\n", msg->message );
#endif

}

void  dumpMessage( Message * msg )
{
	printf("[msg->source]:[%s]\n", msg->source);
	printf("[msg->subject]:[%s]\n", msg->subject);
	printf("[msg->message]:[%s]\n", msg->message);
}

void printMessage( Message * msg )
{
	printf("[%s][%s][%s]\n", msg->source, msg->subject, msg->message );
}
